package org.pathlet.mybatis;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.pathlet.core.InstanceSpace;
import org.pathlet.core.Path;
import org.pathlet.core.exception.ResourceInstanceException;
import org.pathlet.core.exception.ResourceNotFoundException;
import org.pathlet.core.impl.BaseResource;

public class MapperResource extends BaseResource {

	private String scope;

	private Path path;

	private Class mapperClazz;

	public MapperResource(MapperResourceFactory factory, String scope, Path path, Class mapperClazz) {
		super(factory);
		this.scope = scope;
		this.path = path;
		this.mapperClazz = mapperClazz;
	}

	public String getScope() {
		return scope;
	}

	public Path getPath() {
		return path;
	}

	public Class getTargetType() {
		return mapperClazz;
	}

	public void destroyInstance(InstanceSpace context, Object target) { }

	public boolean destroyable() { return false; }

	protected void afterInstanceTarget(InstanceSpace context, Object target) { }

	protected Object doInstanceTarget(InstanceSpace context) {
		try {
			SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(getSqlSessionFactory());
			return sqlSessionTemplate.getMapper(mapperClazz);
		}catch (Exception e) {
			throw new ResourceInstanceException("Failed to instance target!", e, this);
		}
	}

	private MapperResourceFactory getMapperResourceFactory() {
		return (MapperResourceFactory)getFactory();
	}

	private SqlSessionFactory getSqlSessionFactory() {
		return getMapperResourceFactory().sqlSessionFactory;
	}

}

